<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\StoreApply;
use App\Models\Store;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class MerchantAuthController extends Controller
{
    /**
     * 商家登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $username = $request->input('param.username');
        $password = $request->input('param.password');

        if (empty($username) || empty($password)) {
            return response()->json([
                'result' => 0,
                'msg' => '用户名和密码不能为空',
                'data' => []
            ]);
        }

        try {
            // 查找商家申请记录
            $storeApply = StoreApply::where('username', $username)->first();
            
            if (!$storeApply) {
                return response()->json([
                    'result' => 0,
                    'msg' => '用户名不存在',
                    'data' => []
                ]);
            }

            // 验证密码
            if (!Hash::check($password, $storeApply->password)) {
                return response()->json([
                    'result' => 0,
                    'msg' => '密码错误',
                    'data' => []
                ]);
            }

            // 检查申请状态
            if ($storeApply->status == 0) {
                return response()->json([
                    'result' => 0,
                    'msg' => '申请正在审核中，请耐心等待',
                    'data' => []
                ]);
            } elseif ($storeApply->status == -1) {
                return response()->json([
                    'result' => 0,
                    'msg' => '申请被驳回，请联系客服',
                    'data' => []
                ]);
            } elseif ($storeApply->status == 1) {
                // 申请通过，查找对应的门店
                $store = Store::where('uid', $storeApply->uid)->first();
                
                if (!$store) {
                    return response()->json([
                        'result' => 0,
                        'msg' => '门店信息不存在，请联系客服',
                        'data' => []
                    ]);
                }

                // 生成token
                $token = Str::random(60);
                
                // 更新token（这里简化处理，实际项目中应该使用JWT或类似机制）
                $storeApply->remember_token = $token;
                $storeApply->save();

                return response()->json([
                    'result' => 1,
                    'msg' => '登录成功',
                    'data' => [
                        'token' => $token,
                        'merchant' => [
                            'id' => $store->id,
                            'username' => $storeApply->username,
                            'realname' => $storeApply->realname,
                            'mobile' => $storeApply->mobile,
                            'store_name' => $store->store_name,
                            'status' => $store->operating_state == 0 ? 1 : 0
                        ]
                    ]
                ]);
            }

            return response()->json([
                'result' => 0,
                'msg' => '未知状态，请联系客服',
                'data' => []
            ]);

        } catch (\Exception $e) {
            \Log::error('商家登录失败: ' . $e->getMessage());
            return response()->json([
                'result' => 0,
                'msg' => '登录失败，请重试',
                'data' => []
            ]);
        }
    }

    /**
     * 获取商家信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function profile(Request $request)
    {
        try {
            $token = $request->header('Authorization');
            if (!$token) {
                return response()->json([
                    'result' => 0,
                    'msg' => '未授权访问',
                    'data' => []
                ]);
            }

            // 查找商家申请记录
            $storeApply = StoreApply::where('remember_token', $token)->first();
            
            if (!$storeApply) {
                return response()->json([
                    'result' => 0,
                    'msg' => '无效的token',
                    'data' => []
                ]);
            }

            // 查找对应的门店
            $store = Store::where('uid', $storeApply->uid)->first();
            
            if (!$store) {
                return response()->json([
                    'result' => 0,
                    'msg' => '门店信息不存在',
                    'data' => []
                ]);
            }

            $information = json_decode($storeApply->information, true);

            return response()->json([
                'result' => 1,
                'msg' => '获取成功',
                'data' => [
                    'id' => $store->id,
                    'username' => $storeApply->username,
                    'realname' => $storeApply->realname,
                    'mobile' => $storeApply->mobile,
                    'store_name' => $information['store_name'] ?? '',
                    'address' => $information['address'] ?? '',
                    'business_hours' => ($information['business_hours_start'] ?? '') . ' - ' . ($information['business_hours_end'] ?? ''),
                    'status' => $store->operating_state == 0 ? 1 : 0,
                    'created_at' => $store->created_at
                ]
            ]);

        } catch (\Exception $e) {
            \Log::error('获取商家信息失败: ' . $e->getMessage());
            return response()->json([
                'result' => 0,
                'msg' => '获取信息失败',
                'data' => []
            ]);
        }
    }

    /**
     * 获取今日统计数据
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function todayStats(Request $request)
    {
        try {
            $token = $request->header('Authorization');
            if (!$token) {
                return response()->json([
                    'result' => 0,
                    'msg' => '未授权访问',
                    'data' => []
                ]);
            }

            // 查找商家申请记录
            $storeApply = StoreApply::where('remember_token', $token)->first();
            
            if (!$storeApply) {
                return response()->json([
                    'result' => 0,
                    'msg' => '无效的token',
                    'data' => []
                ]);
            }

            // 查找对应的门店
            $store = Store::where('uid', $storeApply->uid)->first();
            
            if (!$store) {
                return response()->json([
                    'result' => 0,
                    'msg' => '门店信息不存在',
                    'data' => []
                ]);
            }

            // 这里应该查询实际的统计数据，暂时返回模拟数据
            $stats = [
                'orders' => rand(5, 20),
                'revenue' => '¥' . rand(500, 2000),
                'products' => rand(20, 100),
                'customers' => rand(3, 15)
            ];

            return response()->json([
                'result' => 1,
                'msg' => '获取成功',
                'data' => $stats
            ]);

        } catch (\Exception $e) {
            \Log::error('获取统计数据失败: ' . $e->getMessage());
            return response()->json([
                'result' => 0,
                'msg' => '获取统计数据失败',
                'data' => []
            ]);
        }
    }
}
